package com.weetop.aklyscan.activity;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseFragment;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.InStockItemBean;
import com.weetop.aklyscan.bean.ProductInfo;
import com.weetop.aklyscan.bean.TransferBoxBean;
import com.weetop.aklyscan.bean.TypeInfo;
import com.weetop.aklyscan.bean.ZXGoodsInfo;
import com.weetop.aklyscan.presenter.ZxProductPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.utils.widget.MyDialogUtil;
import com.weetop.aklyscan.view.ZxProductView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class Fragment_zx_op_product extends BaseFragment<ZxProductPresent> implements ZxProductView {
    private static final int HUOJIA_CODE = 12000;
    private static final int REQUEST_HUOJIA_CODE_SCAN_ONE = 22000;
    String xiangCode, orderID;

    @BindView(R.id.rcy_product)
    RecyclerView rcyProduct;
    Unbinder unbinder;
    @BindView(R.id.et_zzx_code)
    TextView etZzxCode;
    //    @BindView(R.id.et_ck_name)
//    EditText etCkName;
//    @BindView(R.id.et_ck_postion)
//    EditText etCkPostion;
    @BindView(R.id.btn_save)
    QMUIButton btnSave;
    @BindView(R.id.qingkong)
    TextView qingkong;
    @BindView(R.id.bianma)
    TextView bianma;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.orderid)
    TextView orderid;
    @BindView(R.id.order_type_spinner)
    TextView order_type_spinner;
    private CommonRecyclerAdapter<InStockItemBean> adapter;
    private List<InStockItemBean> list = new ArrayList<>();
    private int alreadyInStockCount;
    private String barcode;
    private String boxCode;
    boolean bSave = true;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
            }
        }
    };

    @Override
    protected ZxProductPresent createPresenter() {
        return new ZxProductPresent(this, mActivity);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_zx_product, null);
        unbinder = ButterKnife.bind(this, view);
        rcyProduct.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonRecyclerAdapter<InStockItemBean>(mActivity, R.layout.item_product, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InStockItemBean item, int position) {
                helper.setText(R.id.tv_id, position + 1 + "");
                helper.setText(R.id.tv_code, item.getGoods_code());
                String product_name = TextUtils.isEmpty(item.getGoods_name()) ? "-" : item.getGoods_name();
                String product_model = TextUtils.isEmpty(item.getGoods_model()) ? "-" : item.getGoods_model();
                helper.setText(R.id.tv_name, product_name);
                helper.setText(R.id.tv_model, product_model);
//                EditText etCount = helper.getView(R.id.et_count);
//                if (item.getStatus() == 0) {
                //产品数量不可修改
//                    setEditTextEnable(etCount, false);
                helper.setVisible(R.id.btn_remove, View.VISIBLE);
                helper.setOnClickListener(R.id.btn_remove, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (BaseUtils.fastClick()) {
                            if (list.size() > position) {
                                list.remove(position);
                                adapter.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
//                } else {
//                    helper.setVisible(R.id.btn_remove, View.INVISIBLE);
//                }
            }
        };
        rcyProduct.setAdapter(adapter);
        type.setTag(0);
//        onBarcodeEvent("1800000043");
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                onBarcodeEvent("CPCG202104190001");
////                handler.postDelayed(new Runnable() {
////                    @Override
////                    public void run() {
////                        onBarcodeEvent("CPCG202104190001");
////                    }
////                }, 2000);
//            }
//        }, 2000);
        return view;
    }

    @Override
    public void getSearchResultSuccess(BaseModel<TransferBoxBean> o) {
        TransferBoxBean data = o.getData();
        barcode = data.getBarcode();
        etZzxCode.setText(barcode);
//        etCkName.setText(data.getTier_name());
//        etCkPostion.setText(data.getTier_code());
        List<TransferBoxBean.ItemsBean> items = data.getItems();
        list.clear();
        if (items != null && items.size() > 0) {
            for (int i = 0; i < items.size(); i++) {
                TransferBoxBean.ItemsBean item = items.get(i);
                //产品类型：1产品；2配件
                if (item.getProduct_type() == 1) {
                    InStockItemBean goodsItems = new InStockItemBean();
                    goodsItems.setGoods_code(item.getProduct_code());
                    goodsItems.setGoods_name(item.getProduct_name());
                    goodsItems.setGoods_type(item.getProduct_type());
                    goodsItems.setCount(item.getNumber());
                    //状态:-1已作废；0未入库；1在库里；2未出库；3已出库
                    goodsItems.setStatus(1);
                    list.add(goodsItems);
                }
            }
        }
        alreadyInStockCount = list.size();
        adapter.replaceAll(list);
    }

    @Override
    public void getProductInfSuccess(BaseModel<ProductInfo> o) {
        ProductInfo data = o.getData();
        InStockItemBean goodsItems = new InStockItemBean();
        goodsItems.setGoods_code(data.getGoods_sn());
        goodsItems.setGoods_name(data.getGoods_name());
        //产品类型：1产品；2配件
        goodsItems.setGoods_type(1);
        goodsItems.setCount(1);
        //状态:-1已作废；0未入库；1在库里；2未出库；3已出库
        goodsItems.setStatus(0);
        list.add(goodsItems);
        adapter.add(goodsItems);
    }

    @Override
    public void saveZxSuccess(BaseModel<Object> o) {
//        mPresenter.searchList(boxCode);
//        ToastUtils.showShort("保存成功");
        etZzxCode.setText(xiangCode);
        playRing("shujuyouxiao.mp3");
        etZzxCode.setBackgroundResource(R.drawable.et_grey);
        if (TextUtils.isEmpty(orderid.getText().toString().trim())) {
            orderid.setBackgroundResource(R.drawable.et_yellow);
        }
    }

    @Override
    public void getInto08Success(BaseModel<ZXGoodsInfo> o) {
        ZXGoodsInfo data = o.getData();
        InStockItemBean goodsItems = new InStockItemBean();
        goodsItems.setGoods_code(data.getSerial_code());
        goodsItems.setGoods_name(data.getGoods_name());
        goodsItems.setGoods_model(data.getGoods_model());
        goodsItems.setAudio_url(data.getAudio_url());
        goodsItems.setCount(1);
        goodsItems.setStatus(data.getStatus());
        if (data.getStatus() > 0) {
            ToastUtil.getInstance()._short(getActivity(), "产品已入库");
//            playUrl(goodsItems.getAudio_url(), 0);
            playUrl("", 0);
//            playRing("wuxiao.mp3");
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getGoods_code().equals(goodsItems.getGoods_code())) {
                MyDialogUtil.showDialog(getActivity(), "数据无效已删除");
//                playUrl(goodsItems.getAudio_url(), 0);
                playUrl("", 0);
//                playRing("wuxiao.mp3");
                return;
            }
        }
        if (((int) type.getTag()) == 0) {
            if (list.size() != 0 && !list.get(0).getGoods_model().equals(goodsItems.getGoods_model())) {
                MyDialogUtil.showDialog(getActivity(), "数据无效已删除");
//                playUrl(goodsItems.getAudio_url(), 0);
                playUrl("", 0);
                return;
            }
        }
        orderid.setBackgroundResource(R.drawable.et_grey);
        list.add(goodsItems);
        adapter.add(goodsItems);
        rcyProduct.smoothScrollToPosition(list.size());
        playUrl(goodsItems.getAudio_url(), 1);
//        playRing("luruchenggong.mp3");
        //状态:-1已作废；0未入库；1在库里；2未出库；3已出库
    }

    @Override
    public void getInto09Success(BaseModel<Object> o) {
        bSave = true;
        ToastUtil.getInstance()._short(getActivity(), "操作成功");

        list.clear();
        adapter.clear();
        adapter.notifyDataSetChanged();
        etZzxCode.setText("");
        playRing("zhuangxiangwancheng.mp3");
    }

    @Override
    public void getInto25Success(BaseModel<Object> o) {
        orderid.setText(orderID);
        playRing("shujuyouxiao.mp3");
        orderid.setBackgroundResource(R.drawable.et_grey);
    }

    @Override
    public void onDataError() {
        playRing("shujuwuxiao.mp3");
    }

    @Override
    public void onError() {
        MyDialogUtil.showDialog(getActivity(), "数据无效已删除");
        playRing("wuxiao.mp3");
    }

    @Override
    public void onUpFail(String mag) {
        bSave = true;
        MyDialogUtil.showDialog(getActivity(), mag);
        playRing("wuxiao.mp3");
    }

    /**
     * 设置EditText是否可编辑
     *
     * @param editText 设置的editText对象
     * @param enable   是否可编辑
     */
    private void setEditTextEnable(EditText editText, boolean enable) {
        if (enable) {
            editText.setFocusableInTouchMode(true);
            editText.setFocusable(true);
            editText.requestFocus();
        } else {
            editText.setFocusable(false);
            editText.setFocusableInTouchMode(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.record, R.id.btn_save, R.id.qingkong, R.id.type, R.id.qingkong1, R.id.order_type_spinner})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.record:
                orderid.setText("CPCG202109140001");
                if (TextUtils.isEmpty(orderid.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(getActivity(), "订单号不能为空");
                    return;
                }
                Intent intent = new Intent(getActivity(), MatterBoxRecordListActivity.class);
                intent.putExtra("order_sn",orderid.getText().toString().trim());
                intent.putExtra("order_type", "1");
                getActivity().startActivity(intent);
                break;
            case R.id.btn_save:
                try {
                    if (BaseUtils.fastClick()) {
                        if (!bSave) {
                            return;
                        }
                        if (TextUtils.isEmpty(orderid.getText().toString().trim())) {
                            ToastUtil.getInstance()._short(getActivity(), "订单号不能为空");
                            return;
                        }
                        if (TextUtils.isEmpty(etZzxCode.getText().toString().trim())) {
                            ToastUtil.getInstance()._short(getActivity(), "中装箱编号不能为空");
                            return;
                        }
                        bSave = false;
                        String goods_sns = "";
                        JSONArray jsonArray = new JSONArray();
                        JSONObject tmpObj = null;
                        for (int i = 0; i < list.size(); i++) {
                            tmpObj = new JSONObject();
                            tmpObj.put("serial_code", list.get(i).getGoods_code());
                            tmpObj.put("goods_model", list.get(i).getGoods_model());
                            tmpObj.put("goods_name", list.get(i).getGoods_name());
                            tmpObj.put("num", list.get(i).getCount());
                            jsonArray.put(tmpObj);
                            tmpObj = null;
                        }
                        if (list.size() > 0) {
                            Log.e("TAG", "onViewClicked: " + goods_sns);
                            mPresenter.Into09(orderid.getText().toString().trim(), "1", etZzxCode.getText().toString().trim(), jsonArray);
                        } else {
                            ToastUtils.showShort("无新增产品");
                            bSave = true;
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.qingkong:
                etZzxCode.setText("");
                playRing("qingkong.mp3");
                etZzxCode.setBackgroundResource(R.drawable.et_yellow);
                orderid.setBackgroundResource(R.drawable.et_grey);
                break;
            case R.id.qingkong1:
                orderid.setText("");
                playRing("qingkong.mp3");
                if (TextUtils.isEmpty(etZzxCode.getText().toString().trim())) {
                    etZzxCode.setBackgroundResource(R.drawable.et_yellow);
                    orderid.setBackgroundResource(R.drawable.et_grey);
                } else {
                    orderid.setBackgroundResource(R.drawable.et_yellow);
                }
                break;
            case R.id.type:
                XPopup.get(getActivity()).asCenterList("请选择类型", new String[]{"同型号", "异型号"},
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                type.setTag(position);
                                type.setText(text);
                            }
                        })
                        .show();
                break;
            case R.id.order_type_spinner:
                XPopup.get(getActivity()).asCenterList("请选择凭证类型", new String[]{"产品采购"},
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                order_type_spinner.setText(text);
                            }
                        })
                        .show();
                break;
        }
    }

    public void onBarcodeEvent(String code) {
        System.out.println("扫描结果1：" + code);
        if (TextUtils.isEmpty(etZzxCode.getText().toString().trim())) {
            xiangCode = code;
            mPresenter.saveZx(code);
        } else if (TextUtils.isEmpty(orderid.getText().toString().trim())) {
            orderID = code;
            mPresenter.Into25("1", code);
        } else {
            if (TextUtils.isEmpty(orderid.getText().toString().trim())) {
                ToastUtil.getInstance()._short(getActivity(), "订单号不能为空");
                return;
            }
            mPresenter.Into08("1", code, orderid.getText().toString().trim());
        }
    }

    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();
    private boolean isPlay;

    private void playRing(String fileName) {
        try {
            isPlay = false;
            assetManager = getActivity().getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName) || fileName.equals("null")) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            isPlay = true;
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (isPlay) {
                        if (i == 1) {
                            playRing("luruchenggong.mp3");
                        } else {
                            playRing("wuxiao.mp3");
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        if (player.isPlaying()) {
            player.stop();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        player.release();
        super.onDestroy();
    }
}